<script setup>
import { onMounted, ref, nextTick } from "vue";
import { Edit, Delete, View, CloseBold } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import axios from "axios";
import { SrtingToNum, levelSrtingToNum } from "@/utils/typeMap";
import {
  postPaperApply,
  postPaperSearch,
  postPaperDel,
  postPaperUpdate,
  postPaperEvidence,
  postPaperNoAward,
} from "@/api/paper";

const total = ref(0);
const pagenum = ref(1);
const pagesize = ref(7);
const datalist = ref([]); //用来存返回的数据
const multipleTableRef = ref();
const multipleSelection = ref([]);
const levelText = [
  "SCI一区",
  "SCI二区",
  "SCI三区",
  "SCI四区",
  "EI中文会议",
  "EI英文会议",
  "中文核心期刊",
  "中文普通期刊",
];
const selectable = (row) => ![1, 2].includes(row.id);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  console.log("val", val);
};

const getApplyList = async () => {
  const res = await postPaperSearch(pagenum.value, pagesize.value);
  if (res.code) {
    //提示删除失败
    ElMessage.error("获取失败");
    return;
  }
  total.value = res.count;
  datalist.value = res.data;
  // console.log("list", res);
  //获取申请列表
};

const sizeChange = async () => {
  //页面发生变化
  getApplyList();
};

onMounted(() => {
  getApplyList();
});

const dialogVisible = ref(false); //控制弹窗可见
const diglogDisable = ref(false); //控制表单禁用
const diglogButton = ref(1); //控制按钮显示，1：提交申请 2：编辑  3：取消编辑和提交编辑

const diaFrom = ref({
  id: "",
  topic: "", //可见性
  type: "",
  title: "",
  paperAbstract: "",
  participantMembers: "",
  teamRank: "",
  certificate: "", //但这个有可见性,这是证书
  status: "", //但这个有可见性
});
const typeText = ["论文", "专利", "软著"];
const statusText = {
  0: "待审批",
  1: "审批通过",
  2: "审批失败",
  3: "提前结束",
  4: "等待认证",
  5: "认证成功",
  6: "认证失败",
};
//对应六个颜色
const statsColr = [
  "#9C27B0",
  "#409EFF",
  "#F56C6C",
  "#E6A23C",
  "#9C27B0",
  "#67C23A",
  "#F56C6C",
];

async function fileUrlToFileObject(fileUrl, filename) {
  try {
    // 使用 fetch 读取本地文件
    const response = await fetch(fileUrl);

    // 确保响应成功
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    // 将响应转换为 Blob 对象
    const blob = await response.blob();

    // 创建 File 对象
    const file = new File([blob], filename, {
      type: blob.type,
    });

    return file;
  } catch (error) {
    console.error("Error converting file URL to File object:", error);
    return null;
  }
}

const handleClose = async () => {
  diaFrom.value.type = SrtingToNum(diaFrom.value.type);
  // console.log("提交了申请", diaFrom.value.type);
  dialogVisible.value = false;
  diglogButton.value = 1;
  copyform.value = {};
  getApplyList();
};

const addApply = async () => {
  diaFrom.value = {};
  //添加申请,弹窗确认时调用
  diglogDisable.value = false;
  dialogVisible.value = true;
  nextTick(() => {
    applyform.value.clearValidate();
  });
};

const applyform = ref();
const applyformrules = ref({
  type: [{ required: true, message: "请选择类型", trigger: "blur" }],
  title: [{ required: true, message: "请填写标题", trigger: "blur" }],
  paperAbstract: [{ required: true, message: "请填写摘要", trigger: "blur" }],
  participantMembers: [
    { required: true, message: "请填写参与成员", trigger: "blur" },
  ],
  teamRank: [{ required: true, message: "请填写团队排名", trigger: "blur" }],
});
const submitApply = async () => {
  await applyform.value.validate();
  // console.log("test", test);
  diaFrom.value.type = SrtingToNum(diaFrom.value.type);
  //添加申请,弹窗确认时调用
  const res = await postPaperApply(diaFrom.value);
  if (res.code) {
    //提示删除失败
    ElMessage.error("添加失败");
    return;
  }
  ElMessage.success("已添加申请");
  getApplyList();
  dialogVisible.value = false;
  if (diglogDisable.value == true) {
    diglogDisable.value = false;
  }
};

const delApply = async (id) => {
  //这里对的不是表格是表单
  const res = await postPaperDel(id);
  if (res.code) {
    //提示删除失败
    ElMessage.error("删除失败");
    return;
  }
  ElMessage.success("已删除该申请");
  getApplyList();
};

const delMulApply = async () => {
  //批量删除，未完善
  //参数直接拿数组const multipleSelection = ref([]);
};

const concelApply = async () => {
  //取消申请
  dialogVisible.value = false;
  diaFrom.value = {};
};

const preView = async (row) => {
  //用obssgin方法row对应的值赋给diaFrom
  dialogVisible.value = true;
  diglogDisable.value = true;
  diglogButton.value = 2;
  // console.log(row);
  //改成深拷贝
  // diaFrom.value = row;
  diaFrom.value = JSON.parse(JSON.stringify(row));
  diaFrom.value.type = typeText[row.type]; //这是为了渲染，还要映射回去
  // console.log(diaFrom.value);
};

const copyform = ref();

const Editapply = () => {
  //编辑
  diglogButton.value = 3;
  //解开禁用
  diglogDisable.value = false;
  //这里要写深拷贝
  copyform.value = JSON.parse(JSON.stringify(diaFrom.value));
  // console.log("copy", copyform.value);
};

const submitEditApply = async () => {
  await applyform.value.validate();
  //提交个更改
  //先判断有没有更改
  if (diaFrom.value === copyform.value) {
    ElMessage.error("没有更改");
    return;
  }
  diaFrom.value.type = SrtingToNum(diaFrom.value.type);

  // console.log("提交了更改");
  const res = await postPaperUpdate(diaFrom.value);
  if (res.code) {
    ElMessage.error("提交失败");
    return;
  }
  diaFrom.value.type = typeText[diaFrom.value.type]; //还要映射回来显示才正确
  diglogButton.value = 2;
  diglogDisable.value = true;
  copyform.value = JSON.parse(JSON.stringify(diaFrom.value));
  ElMessage.success("提交成功");
};

const endApply = async (id) => {
  const res = await postPaperNoAward(id);
  if (!res.code) {
    ElMessage.success("已提前结束");
    getApplyList();
  } else {
    ElMessage.error("提前结束失败，请重试");
  }
};

const fileform = ref({
  id: "",
  type: "",
  awardTime: "",
  topic: "",
  file: "",
  certificate: "",
});
const imgUrl = ref("");

const uploadVisible = ref(false);

const uploadform = ref();

const uploadHandleClose = async () => {
  uploadVisible.value = false;
  fileform.value = {};
  imgUrl.value = "";
};

const uploadformrules = ref({
  certificate: [
    { required: true, message: "请上传图片", trigger: "blur" },
    { type: "file", message: "请上传图片", trigger: ["blur", "change"] },
  ],
  topic: [{ required: true, message: "请填写标题", trigger: "blur" }],
  awardTime: [{ required: true, message: "请选择时间", trigger: "blur" }],
});

const uploadpic = async (row) => {
  //上传图片
  if (row.status == 5) {
    ElMessage.error("已完成认证，无需上传");
    return;
  }
  uploadVisible.value = true;
  // fileform.value.id = row.id;
  // fileform.value.topic = row.topic;
  //深拷贝
  fileform.value = JSON.parse(JSON.stringify(row));
  if (row.certificate != null) {
    const imgu = row.certificate.split("/").pop(); //只要文件名
    fileform.value.file = fileform.value.certificate;
    const file = await fileUrlToFileObject(fileform.value.file, imgu);
    // console.log("file");
    // console.log(file);
    fileform.value.file = file;
    // console.log("row", fileform.value.file);
  }
  nextTick(() => {
    uploadform.value.clearValidate();
  });
};

const onSelectFile = (uploadFile) => {
  imgUrl.value = URL.createObjectURL(uploadFile.raw); // 预览图片
  // 立刻将图片对象，存入 formModel.value.cover_img 将来用于提交
  //深拷贝
  // fileform.value.file = JSON.parse(JSON.stringify(uploadFile.raw));
  fileform.value.file = uploadFile.raw;
};
const submitPicApply = async () => {
  await uploadform.value.validate();
  // 上传图片
  // console.log("fileform", fileform.value);
  const fd = new FormData();
  fd.append("applicationId", fileform.value.id);
  fd.append("topic", fileform.value.topic);
  fd.append("awardTime", fileform.value.awardTime);

  // 判断是否有更改
  // console.log("fileform", fileform.value.file);

  // 判断file是否为文件，如果不是文件，抛出错误并返回
  if (fileform.value.file instanceof File) {
    // 再判断一下，不是图片也不行jpg,jpeg,png
    if (
      fileform.value.file.type !== "image/jpeg" &&
      fileform.value.file.type !== "image/png"
    ) {
      ElMessage.error("上传文件类型不正确");
      return;
    }

    // 检查文件大小是否超过2MB
    const maxFileSize = 2 * 1024 * 1024; // 2MB in bytes
    if (fileform.value.file.size > maxFileSize) {
      ElMessage.error("上传文件大小不能超过2MB");
      return;
    }

    fd.append("file", fileform.value.file);
  } else {
    ElMessage.error("请选择文件");
    return;
  }

  await postPaperEvidence(fd);
  ElMessage.success("上传成功,未认证前点击图片可更改");
  uploadHandleClose();
  getApplyList();
};

//文件批量下载和表单校验，附件添加时间
</script>

<template>
  <el-card class="box">
    <div class="top">
      <span style="font-size: 25px; color: #203857">论文/专利/软件提交</span>
      <el-button type="success" @click="addApply"
        ><el-icon><Plus /></el-icon>提交申请</el-button
      >
    </div>
    <el-table
      :data="datalist"
      height="500px"
      stripe
      ref="multipleTableRef"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" :selectable="selectable" width="40" />
      <el-table-column
        type="index"
        label="序号"
        width="55"
        align="center"
      ></el-table-column>
      <el-table-column prop="type" label="申请类型" align="center"
        ><template #="{ row }">
          <span>{{ typeText[row.type] }}</span>
        </template></el-table-column
      >
      <el-table-column
        prop="createTime"
        label="申请时间"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="title"
        label="标题"
        show-overflow-tooltip
        align="center"
      ></el-table-column>
      <el-table-column
        prop="paperAbstract"
        label="内容"
        show-overflow-tooltip
        align="center"
      ></el-table-column>
      <el-table-column
        prop="teamRank"
        label="申请位次"
        align="center"
      ></el-table-column>
      <el-table-column label="上传图片" align="center">
        <!-- 这里要做图片预览或者文件，都要用插槽，做点击图片预览效果，要看变量值确定是否显示 -->
        <!-- 没有url就实现按钮，否则就是url -->
        <template #="{ row }">
          <div v-if="row.status == 1 || row.status == 6">
            <el-button
              title="上传图片"
              type="primary"
              @click="uploadpic(row)"
              size="small"
              plain
              icon="Upload"
              circle
            ></el-button>
            <el-popconfirm
              :title="`确定提前结束流程吗？`"
              width="250px"
              icon="Delete"
              @confirm="endApply(row.id)"
            >
              <template #reference>
                <el-button
                  title="未获奖"
                  type="warning"
                  size="small"
                  icon="CloseBold"
                  circle
                  plain
                ></el-button>
              </template>
            </el-popconfirm>
          </div>
          <div v-else>
            <img
              class="imgfile"
              v-if="row.certificate && (row.status == 4 || row.status == 5)"
              :src="row.certificate"
              @click="uploadpic(row)"
            />
            <span v-else>暂无需</span>
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column
        prop="finalLevel"
        label="认定等级"
        align="center"
      ></el-table-column> -->
      <el-table-column prop="status" label="申请状态" align="center">
        <template #="{ row }">
          <span :style="{ color: statsColr[row.status] }">{{
            row.status != 5
              ? statusText[row.status]
              : row.finalLevel <= 7
              ? levelText[row.finalLevel]
              : statusText[row.status]
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right">
        <template #="{ row }">
          <el-button
            title="查看详情"
            type="primary"
            size="small"
            icon="View"
            circle
            plain
            @click="preView(row)"
          ></el-button>
          <!-- 气泡窗,模板字符串 -->
          <el-popconfirm
            :title="`确定删除吗？`"
            width="250px"
            icon="Delete"
            @confirm="delApply(row.id)"
          >
            <template #reference>
              <el-button
                title="删除申请"
                plain
                type="danger"
                size="small"
                icon="Delete"
                circle
                :disabled="row.status >= 1"
              ></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
        @size-change="sizeChange"
        @current-change="getApplyList"
        :pager-count="9"
        v-model:current-page="pagenum"
        v-model:page-size="pagesize"
        :page-sizes="[3, 5, 7, 9, 15, 30, 60]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
      />
    </div>
    <el-dialog
      v-model="dialogVisible"
      width="600"
      :before-close="handleClose"
      draggable
    >
      <template #header="{}">
        <div class="my-header">
          <img class="imgtitle" src="@/assets/images/logo.jpg" />
          <span class="titleClass">申请提交</span>
        </div>
      </template>
      <el-form
        label-width="auto"
        :model="diaFrom"
        :disabled="diglogDisable"
        :rules="applyformrules"
        ref="applyform"
      >
        <el-form-item label="申请类型" prop="type">
          <el-select
            v-model="diaFrom.type"
            placeholder="请选择申请类型"
            style="height: 35px; width: 150px"
          >
            <el-option label="论文" value="论文"></el-option>
            <el-option label="专利" value="专利"></el-option>
            <el-option label="软著" value="软著"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="diaFrom.title"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="paperAbstract">
          <el-input
            v-model="diaFrom.paperAbstract"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
          ></el-input>
        </el-form-item>
        <el-form-item label="团队成员" prop="participantMembers">
          <el-input
            v-model="diaFrom.participantMembers"
            placeholder="请用逗号分隔"
          ></el-input>
        </el-form-item>
        <el-form-item label="排名" prop="teamRank">
          <el-input
            v-model="diaFrom.teamRank"
            placeholder="只需要填写一个数字"
          ></el-input>
        </el-form-item>
        <el-form-item label="期刊" v-if="diaFrom.topic">
          <el-input
            v-model="diaFrom.topic"
            placeholder="只需要填写一个数字"
          ></el-input>
        </el-form-item>
        <el-form-item label="证书" v-if="diaFrom.certificate">
          <el-image
            :src="diaFrom.certificate"
            style="width: 100px; height: 100px"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="[diaFrom.certificate]"
            :initial-index="4"
            fit="cover"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <div v-if="diglogButton == 1">
            <el-button @click="concelApply">取消提交</el-button>
            <el-button type="primary" @click="submitApply">
              确认提交
            </el-button>
          </div>
          <div v-if="diglogButton == 2">
            <el-button
              type="primary"
              @click="Editapply"
              :disabled="diaFrom.status != 0"
            >
              编辑
            </el-button>
          </div>
          <div v-if="diglogButton == 3">
            <el-button type="primary" @click="submitEditApply()">
              提交更改
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="uploadVisible"
      width="600"
      :before-close="uploadHandleClose"
      draggable
    >
      <template #header="{}">
        <div class="my-header">
          <img class="imgtitle" src="@/assets/images/logo.jpg" />
          <span class="titleClass">上传认证材料</span>
        </div>
      </template>
      <el-form
        label-width="auto"
        :model="fileform"
        :rules="uploadformrules"
        ref="uploadform"
      >
        <el-form-item label="期刊名称" v-if="fileform.type == 0" prop="topic">
          <el-input v-model="fileform.topic"></el-input>
        </el-form-item>
        <el-form-item label="见刊/获得时间" prop="awardTime">
          <el-date-picker
            v-model="fileform.awardTime"
            type="date"
            placeholder="Pick a Date"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD hh:mm:ss"
          />
        </el-form-item>
        <el-form-item label="图片材料" prop="certificate">
          <el-upload
            class="avatar-uploader"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="onSelectFile"
          >
            <img v-if="imgUrl" :src="imgUrl" class="avatar" />
            <div v-else>
              <img
                v-if="fileform.certificate"
                :src="fileform.certificate"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPicApply">
            确认提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<style scoped lang="scss">
.box {
  padding: 15px;
  //开启相对定位
  .el-table {
    margin-bottom: 2vh;
  }
}
.top {
  display: flex;
  width: 100%;

  height: 50px;
  line-height: 50px;

  //垂直居中
  align-items: center;
  .el-button {
    margin-left: 20px;
  }
  margin-bottom: 15px;
}
.my-header {
  display: flex;
  height: 50px;
  line-height: 50px;
  .titleClass {
    font-size: 25px;
  }
  .imgtitle {
    width: 50px;
    height: 50px;
    margin-right: 10px;
  }
  .titleendClass {
    margin-left: 10px;
    font-size: 20px;
  }
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.imgfile {
  width: 80px;
  height: 80px;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
